package com.hmall.item;

import cn.hutool.json.JSONUtil;
import com.hmall.common.pojo.Item;
import com.hmall.item.mapper.ItemMapper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;

/**
 * TODO
 *
 * @Author wangxinyi
 * @Date 2024/11/22 10:17
 */
@SpringBootTest
public class BatchInsert {

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private RestHighLevelClient client;
    @Test
    public void insertItems() throws IOException {
        // 批量查询酒店数据
        List<Item> itemList = itemMapper.selectList(null);

        // 1.创建Request
        BulkRequest request = new BulkRequest();
        // 2.准备参数，添加多个新增的Request
        for (Item item : itemList) {
            // 2.2.创建新增文档的Request对象
            request.add(new IndexRequest("items")
                    .id(item.getId().toString())
                    .source(JSONUtil.toJsonStr(item), XContentType.JSON));
        }
        // 3.发送请求
        client.bulk(request, RequestOptions.DEFAULT);
    }
}
